<template>
  <div>
    <Dialog
        :buttons="dialogConfig.buttons"
        :show="dialogConfig.show"
        :showCancel="false"
        :title="dialogConfig.title"
        MaxWidth="1000px"
        width="800px"
        @Close="dialogConfig.show = false">
      <div class="dialog-panel">
        <div class="bg">
          <img alt="" src="@/assets/img/login_bg2.png">
        </div>
        <div class="login-register form-main">
          <div class="tab-panel">
            <div :class="[onType == 0 ?'active':'']" @click="showPanel(0)">登录</div>
            <el-divider direction="vertical"/>
            <div :class="[onType == 1 ?'active':'']" @click="showPanel(1)">注册</div>
          </div>
          <el-form  ref="formDataRef" :model="formData" :rules="rules" @submit.prevent>
          <div v-if="onType==0">
              <el-form-item prop="email">
                <el-input v-model="formData.email" clearable placeholder="请输入邮箱" type="text">
                  <template #prefix>
                    <span class="iconfont icon-email"></span>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="formData.password" placeholder="请输入密码" show-password type="password">
                    <template #prefix>
                      <span class="iconfont icon-password"></span>
                    </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="checkCode">
                <div class="check-code-panel">
                  <el-input v-model="formData.checkCode" clearable placeholder="请输入验证码" type="text">
                    <template #prefix>
                      <span class="iconfont icon-checkcode"></span>
                    </template>
                  </el-input>
                  <div @click="fetchNewCaptcha">
                    <img style="margin-left: 10px;height: 42px;" :src="Captcha" alt="服务异常">
                  </div>
                </div>
              </el-form-item>
          </div>
          <div v-if="onType==1">
            <el-form-item prop="username">
              <el-input v-model="formData.username" clearable placeholder="请输入用户名" type="text">
                <template #prefix>
                  <span class="iconfont icon-user"></span>
                </template>
              </el-input>
            </el-form-item>
              <el-form-item prop="email">
                <el-input v-model="formData.email" clearable placeholder="请输入邮箱" type="text">
                  <template #prefix>
                    <span class="iconfont icon-email"></span>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="checkCode">
                <div class="check-code-panel">
                  <el-input v-model="formData.checkCode" clearable placeholder="请输入校验码" type="text">
                    <template #prefix>
                      <span class="iconfont icon-checkcode"></span>
                    </template>
                  </el-input>
                  <el-button :disabled="coldTime || !isEmailValid" style="margin-left: 5px" type="primary" @click="askCode">
                    {{ coldTime > 0 ? `请稍后 ${coldTime} 秒` : '获取校验码' }}
                  </el-button>
                </div>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="formData.password" placeholder="请输入密码" show-password type="password">
                  <template #prefix>
                    <span class="iconfont icon-password"></span>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="repassword">
                <el-input v-model="formData.repassword" placeholder="请确认密码" show-password type="password">
                  <template #prefix>
                    <span class="iconfont icon-password"></span>
                  </template>
                </el-input>
              </el-form-item>
          </div>
            <el-form-item>
              <el-button v-if="onType==0" style="width: 100%;" type="primary"  @click="Gologin">登录</el-button>
              <el-button v-else style="width: 100%;" type="success"  @click="GoRegister">注册</el-button>
              <p> <span v-if="onType==0">登录</span><span v-else>完成注册</span>即代表你同意 <a href="https://www.bilibili.com/protocal/licence.html" style="color: #00a1d6;text-decoration: none" target="_blank">用户协议</a>
                和 <a href="https://www.bilibili.com/blackboard/privacy-pc.html" style="color: #00a1d6;text-decoration: none" target="_blank">隐私政策</a></p>
            </el-form-item>
          </el-form>
          <div class="login-sns-wp" v-if="onType==0">
            <div class="login-sns-title">其他方式登录</div>
            <div class="login-sns-content">
              <div class="login-sns-item">
                <img src="@/assets/images/wx.png" class="login-sns-item-icon">
                <span class="login-sns-name">微信登录</span>
              </div>
              <div class="login-sns-item">
                <img src="@/assets/images/wb.png" class="login-sns-item-icon">
                <span class="login-sns-name">微博登录</span>
              </div>
              <div class="login-sns-item">
                <img src="@/assets/images/qq.png" class="login-sns-item-icon">
                <span class="login-sns-name">QQ登录</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Dialog>
  </div>
</template>
<script setup>
import Dialog from "@/components/Dialog.vue";
const { proxy } = getCurrentInstance();
import {Api} from "@/api/index.js"
import {askCodeServe, CaptchaServe, Login, Register} from "@/api/user";
import {computed, getCurrentInstance, ref, watch} from "vue";
import {ElMessage} from "element-plus";
import Message from "@/utils/Message.js";
import {useLoginStore} from "@/stores/loginStore.js"
import {bus} from "@/utils/mitt.js"
import captcha from "@/data/captcha.json";
import auth_login from "@/data/auth_login.json"
import auth_login_err from "@/data/auth_login_err.json"

// 校验码
const colds = ref(0);
const Captcha = ref(Api.Captcha);
const checkCodeKey = ref("");
const fetchNewCaptcha = async () => {
  colds.value += 1
  if (colds.value <= 5) {
    const res = captcha;
    Captcha.value = res.data.checkCode;
    checkCodeKey.value = res.data.checkCodeKey;
  }else{
    Message.error("验证码刷新过于频繁,请稍后再试!")
  }
};
bus.on("login-copdown",(a)=>{
  if(a==0){
    dialogConfig.value.show = true;
    showPanel(0)
    fetchNewCaptcha()
  }else{
    dialogConfig.value.show = false;
  }
})
const loginCopdown = ref(proxy.$loginCopdown);
const dialogConfig = ref({
  show: false,
  buttons: []
});

const formData = ref({
  email: "",
  password: "",
  checkCode: "",
  repassword: "",
  username: ""
});

const formDataRef = ref()
const showPanel = (type) => {
  formData.value = {
    email: "",
    password: "",
    checkCode: "",
    repassword: "",
    username: ""
  }
  onType.value = type;
}
const onType = ref(0);
const validatePassword = (rule,value,caches)=> {
  if (value == '') {
    caches(new Error('请再次输入密码'))
  }else if(value !== formData.value.password){
    caches(new Error("两次输入的密码不一致"))
  }else{
    caches()
  }
}
const validateUsername = (rule,value,caches)=> {
  if (value.length < 3) {
    caches(new Error('请输入至少3位'))
  } else if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) {
    caches(new Error('用户名不能包含特殊字符，只能是中/英文'))
  }else{
    caches()
  }
}
const rules = ref({
  username: [{validator: validateUsername,trigger:['blur','change']}],
  email: [
      { required: true, message: "请输入邮箱", trigger: "blur" },
      {
          type: "email",
          message: "请输入正确的邮箱地址",
          trigger: ["blur", "change"],
      },
  ],
  password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      {min:6,max:20,message:"密码的长度必须在6-20之间",trigger: ['blur','change']}
  ],
  repassword: [{validator: validatePassword,trigger:['blur','change']},],
  checkCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
const coldTime = ref(0);
let intervalId = ref()
watch(coldTime, (newValue, oldValue) => {
  if (newValue == 0){
    setInterval(()=> clearInterval(intervalId))
  }
});

// 发送验证码方法
const askCode = async () =>{
  if(isEmailValid){
    const res = await askCodeServe(formData.value.email)
    if(res.code == 200){
      Message.success("验证码已发送")
    }else{
      Message.error(res.message)
    }
    coldTime.value = 60
    intervalId = setInterval(()=> coldTime.value--,1000)
  }else{
    ElMessage.warning("请输入正确的电子邮箱")
  }
}

// 登录方法
const Gologin = async () =>{
  formDataRef.value.validate(async (valid)=>{
    if(!valid){
      return;
    }
    let datas = {
      email: formData.value.email,
      password: formData.value.password,
      CodeKey: checkCodeKey.value,
      code: formData.value.checkCode
    }
    let result = []
    if(datas.email==="admin@admin.com"&&datas.password==="123456"){
      result = auth_login;
      Message.success("登录成功")
    }else{
      result = auth_login_err;
      Message.error(result.message)
      return;
    }
    const loginStore = useLoginStore();
    loginStore.setLogin(true)
    loginStore.setToken(result.data.token)
    loginStore.saveUserInfo(result.data)
    dialogConfig.value.show = false;
  })
}

//注册
const GoRegister = async () =>{
  formDataRef.value.validate(async (valid)=>{
    if(!valid){
      return;
    }
    let result = await Register(formData.value.email,formData.value.checkCode,formData.value.username,formData.value.password)
    if(!result){
      return;
    }
    Message.success("注册成功,请登录！")
    showPanel(0)
  })
}
const isEmailValid = computed(()=>/^[\w.-]+@[\w\.]+\.\w+$/.test(formData.value.email))
</script>
<style scoped>
.dialog-panel{
  display: flex;
  align-items: center;
  justify-content: space-between;
  .bg{
    width: 40%;
    height: 30%;
    overflow: hidden;
    img{
      width: 100%;
      height: 100%;
    }
  }
  .form-main{
    padding-right: 15%;
  }
  .login-register{
    width: 300px;
    .tab-panel{
      margin:10px auto;
      display: flex;
      width: 130px;
      font-size: 18px;
      align-items: center;
      justify-content: space-between;
      cursor: pointer;
      .active{
        color: #409EFF;
      }
    }
    .no-user{
      width: 100%;
      display: flex;
      justify-content: center;
    }
    .login-btn{
      width: 100%;
    }
    .bottom-btn{
      width: 100%;
    }
  }
}
.check-code-panel{
  display: flex;
  align-items: center;
  margin-top: -5px;
  width: 100%;
  .input{
    flex: 1;
  }
}
.login-sns-wp{
  text-align: center;
  color: #9499a0;
  .login-sns-content{
    margin-top: 20px;
    display: flex;
    .login-sns-item {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 10px;
      .login-sns-item-icon {
        width: 28px;
        height: 28px;
        margin-right: 8px;
      }
      .login-sns-name {
        text-align: center;
        font-weight: 400;
        font-size: 13px;
        line-height: 16px;
      }
    }
  }
}
</style>